import React from 'react';
import styles from './index.less';
import { Button, Spin } from 'antd';
import { connect } from 'umi';

import { TRDefault, TRMessage } from '#/components';
import { DownSquareOutlined, UploadOutlined, UpSquareOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';

import { PageLoading } from '@/components';
import { useExcel } from '@/hooks';
import { TjArrow, TjChart, TjTable, useTRState } from '@/pages/ETrade/components';

import { default as HeadForm } from './form';
import { getSettlementClassDetail, queryMarketList } from './services';
import { fmtMonthData, getColumns } from './helper';
import { getTreeByCodes } from '@/utils';
import { useThemeChange } from '@/hooks';

const exportKey = 'SettlementCategoryDetailExport';
const SettlementCategoryDetails = ({ buttonPermissions, menuCode }) => {
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    // 初始化三件套
    spinning: true,
    error: '',
    power: [],
    // 数据
    loading: true,
    monthData: null,
    tableColumns: [],
    tableData: [],
    total: 0,
    monthChart: null,
    monthTable: [],
    monthColumns: [],
    openLeft: false,
    openRight: false,
    monthAll: true,
    allData: null,
  });
  const { theme } = useThemeChange();

  React.useEffect(() => {
    init();
  }, []);

  React.useEffect(() => {
    if (state.allData) {
      const { monthChart } = fmtMonthData(state.allData);
      setState({ monthChart });
    }
  }, [theme]);

  /** apis */
  const init = async () => {
    // 权限
    const res = await queryMarketList(menuCode);
    let power = [];
    let error = '';
    if (res?.statusCode === HttpCode.SUCCESS) {
      // tree需要唯一值键，处理一下
      power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      power,
      error,
      spinning: false,
    });
  };

  /** methods */
  const onChangeForm = async (values) => {
    if (!values) return;
    setState({ loading: true });
    let res = await getSettlementClassDetail(values);
    res = res?.data || res;
    const tableData = res?.formList || [];
    const total = res?.totalCapacity || 0;
    const tableColumns = getColumns(tableData);
    const { monthChart, monthTable, monthColumns } = fmtMonthData(
      res?.monthAnalysis,
      values?.marketId,
    );
    setState({
      tableColumns,
      tableData,
      loading: false,
      total,
      monthChart,
      monthTable,
      monthColumns,
      allData: res?.monthAnalysis,
    });
  };

  const _onExport = async () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    useExcel({
      filename: '结算单分类明细报表',
      columns: [...state.tableColumns[0].children, ...state.tableColumns.slice(1)], // 特殊处理下
      data: state.tableData,
      merges: [
        'dataTypeName',
        'transactionAttributesOneName',
        'transactionAttributesTwoName',
        // 'transactionAttributesThreeName',
      ],
    });
  };

  /** render */
  const _renderMain = () => {
    if (state.loading) return null;
    if (!state.tableData?.length) return <TRDefault type="empty" />;
    return (
      <div className={styles.flex}>
        <div
          className={styles.box}
          style={{ width: state.openLeft ? '100%' : state.openRight ? 0 : '50%' }}
        >
          <div className={styles.boxInner}>
            <div>
              <TjArrow
                value={state.openLeft}
                position="right"
                onChange={(openLeft) => setState({ openLeft })}
              />
              <div className={styles.title}>
                <div>
                  <span className={styles.title_name}>结算单分类明细报表</span>
                </div>
                <Button
                  disabled={!state.tableData?.length}
                  style={{ padding: 0 }}
                  type="link"
                  icon={<UploadOutlined />}
                  onClick={_onExport}
                >
                  导出
                </Button>
              </div>
              <div className={styles.total}>
                <span className={styles.gray}>合计装机容量：</span>
                <span className={styles.total_value}>{state.total}</span>
                <span className={styles.gray}>万kW</span>
              </div>
              <div className={styles.scroll}>
                <div className={styles.table}>
                  <TjTable
                    primaryKey={'tableId'}
                    columns={state.tableColumns}
                    dataSource={state.tableData}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div
          className={styles.box}
          style={{ width: state.openRight ? '100%' : state.openLeft ? 0 : '50%' }}
        >
          <TjArrow
            value={state.openRight}
            position="left"
            onChange={(openRight) => setState({ openRight })}
          />
          <div className={styles.boxInner}>
            <div>
              <div className={styles.title}>
                <div>
                  <span className={styles.title_name}>分月分析</span>
                </div>
                <div>
                  <Button
                    style={{ padding: 0 }}
                    type="link"
                    icon={state.monthAll ? <UpSquareOutlined /> : <DownSquareOutlined />}
                    onClick={() => setState({ monthAll: !state.monthAll })}
                  >
                    {state.monthAll ? '收起' : '展开'}
                  </Button>
                </div>
              </div>
              <div className={styles.scroll}>
                {!state.monthTable?.length ? (
                  <TRDefault type="emptysm" />
                ) : (
                  <>
                    <div
                      className={styles.f1}
                      style={!state.monthAll ? { height: '100%' } : { height: '60%' }}
                    >
                      <TjChart option={state.monthChart} />
                    </div>
                    {state.monthAll && (
                      <div className={styles.f0}>
                        <TjTable columns={state.monthColumns} dataSource={state.monthTable} />
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power?.length) return <TRDefault type="lock" />;
  return (
    <Spin spinning={state.loading}>
      <div className={styles.container}>
        <div className={styles.head}>
          <HeadForm power={state.power} onChange={onChangeForm} />
        </div>
        <div className={styles.main}>{_renderMain()}</div>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(SettlementCategoryDetails);
